//
//  ESGTeamInquiryDetailController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/4/8.
//  Copyright © 2020 QDSG. All rights reserved.
//

import UIKit

class ESGTeamInquiryDetailController: BaseViewController {
    
    private let teamId: String
    
    init(teamId: String) {
        self.teamId = teamId
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var viewModel: ESGTeamInquiryViewModel.RowViewModel? {
        didSet {
            tableView.isHidden = false
            tableView.reloadData()
            headerView.updateData(with: viewModel)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.barTintColor = .background
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.navigationBar.barTintColor = .white
    }
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.rowHeight = UITableView.automaticDimension
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.register(DoctorDetailInfoCell.nibForCell(),
                               forCellReuseIdentifier: DoctorDetailInfoCell.reuseIdentifier())
            tableView.register(DoctorReserveCell.nibForCell(),
                               forCellReuseIdentifier: DoctorReserveCell.reuseIdentifier())
            tableView.register(DoctorDetailSectionHeader.nibForCell(),
                               forHeaderFooterViewReuseIdentifier: DoctorDetailSectionHeader.reuseIdentifier())
        }
    }
    
    private lazy var headerView = UINib.loadViewFrom(DoctorDetailHeaderView.self)
}

extension ESGTeamInquiryDetailController {
    private func setupUI() {
        tableView.tableHeaderView = headerView
        headerView.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.size.equalTo(CGSize(width: screenW, height: 120))
        }
    }
    
    private func loadData() {
        HUDTool.showActivity()
        ESGTeamInquiryViewModel.getTeamInquiryDetail(teamId: teamId) { (model, errorMsg) in
            HUDTool.hideActivity()
            guard let m = model else {
                HUDTool.showError(message: errorMsg)
                return
            }
            
            self.viewModel = ESGTeamInquiryViewModel.RowViewModel(model: m)
        }
    }
}

extension ESGTeamInquiryDetailController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRows(in: section) ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: DoctorDetailInfoCell.reuseIdentifier(),
                                                     for: indexPath) as! DoctorDetailInfoCell
            cell.delegate = self
            if let vm = viewModel {
                cell.confiure(with: vm)
            }
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: DoctorReserveCell.reuseIdentifier(),
                                                     for: indexPath) as! DoctorReserveCell
            cell.delegate = self
            if let vm = viewModel?.viewModel(for: indexPath) {
                cell.configure(with: vm)
            }
            return cell
        default:
            return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 1:
            let header = tableView.dequeueReusableHeaderFooterView(
                withIdentifier: DoctorDetailSectionHeader.reuseIdentifier()) as? DoctorDetailSectionHeader
            header?.configure()
            return header
        default:
            return UIView()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 1: return 54
        default: return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 1:
            guard let vm = viewModel?.viewModel(for: indexPath) else { return 0 }
            return vm.cellHeight()
        default:
            return UITableView.automaticDimension
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(for: indexPath), indexPath.section != 0 else { return }
        pushDoctorDetail(with: vm)
    }
}

extension ESGTeamInquiryDetailController: DoctorDetailInfoCellDelegate, DoctorReserveCellDelegate {
    func DoctorDetailInfoCellAction(btn: UIButton) {
        tableView.reloadData()
    }
    
    func doctorReserveCell(_ cell: DoctorReserveCell, willReserveCloud type: DoctorType) {
        guard let indexPath = tableView.indexPath(for: cell),
            let vm = viewModel?.viewModel(for: indexPath) else { return }
        reserveCloud(vm, type: type)
    }
    
    func doctorReserveCell(_ cell: DoctorReserveCell, willReserveAdvisory type: DoctorType) {
        guard let indexPath = tableView.indexPath(for: cell),
            let vm = viewModel?.viewModel(for: indexPath) else { return }
        reserveAdvisory(vm, type: type)
    }
}

extension ESGTeamInquiryDetailController {
    private func pushDoctorDetail(with vm: DoctorReserveRowViewModel) {
        let detailVc = DoctorDetailController(with: vm.doctorId)
        navigationController?.pushViewController(detailVc, animated: true)
    }
    
    private func reserveAdvisory(_ vm: DoctorReserveRowViewModel, type: DoctorType) {
        let model = DoctorDetail(id: vm.doctorId,
                                 deptId: vm.departmentId,
                                 docName: vm.doctorName,
                                 deptName: vm.department,
                                 hospitalName: vm.hospitalName,
                                 jobTitleName: vm.office,
                                 docGoodAtNames: vm.specialty,
                                 thumbnailUrl: vm.thumbnailUrl,
                                 score: vm.score.floatValue,
                                 fee: vm.fee,
                                 diagType: type.rawValue)
        let doctorDetail = DoctorDetailViewModel(model: model,
                                                 selectType: .advisory)
        let adMedicalRecordsVC = AdMedicalRecordsController()
        adMedicalRecordsVC.doctorVm = doctorDetail
        navigationController?.pushViewController(adMedicalRecordsVC, animated: true)
    }
    
    private func reserveCloud(_ vm: DoctorReserveRowViewModel, type: DoctorType) {
        let model = DoctorDetail(id: vm.doctorId,
                                 deptId: vm.departmentId,
                                 docName: vm.doctorName,
                                 deptName: vm.department,
                                 hospitalName: vm.hospitalName,
                                 jobTitleName: vm.office,
                                 docGoodAtNames: vm.specialty,
                                 thumbnailUrl: vm.thumbnailUrl,
                                 score: vm.score.floatValue,
                                 fee: vm.fee,
                                 diagType: type.rawValue)
        let doctorDetail = DoctorDetailViewModel(model: model,
                                                 selectType: .cloud)
        let newCloudVc = NewCloudReserveController(with: doctorDetail)
        navigationController?.pushViewController(newCloudVc, animated: true)
    }
}
